package com.yk.anima.interceptor;

import com.alibaba.fastjson.JSON;
import com.yk.anima.pojo.Admin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;


/**
 * @author xiaokai
 * @create 2021-05-12 10:20:10
 * @desc...自定义拦截器
 */

public class MyInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    Set<String> hashSet = new HashSet<String>();

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //  /webjars/springfox-swagger-ui/springfox.css

        //获得客户端的ip地址 每一个客户端的ip地址都是不相同的
        String servletPath = request.getServletPath();

        System.out.println(servletPath);
        String ip = request.getRemoteAddr();
        String user = stringRedisTemplate.opsForValue().get(ip);
        if (user == null) {
            return false;
        }
        Admin admin = JSON.parseObject(user, Admin.class);
        String userName = admin.getUserName();
        String passWord = admin.getPassWord();
        if (userName != null && passWord != null) {
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("执行完方法之后进执行(Controller方法调用之后)，但是此时还没进行视图渲染");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("整个请求都处理完咯，DispatcherServlet也渲染了对应的视图咯，此时我可以做一些清理的工作了");
    }

}
